package com.hzlx.config;

import com.hzlx.dto.UserDto;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.ReactiveAuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

import java.util.List;
import java.util.stream.Collectors;

// 自定义认证提供者
@Component
@RequiredArgsConstructor
public class LoginReactiveAuthenticationManager implements ReactiveAuthenticationManager {
    private final UserService userService;
    private final PasswordEncoder passwordEncoder;
    @Override
    public Mono<Authentication> authenticate(Authentication authentication) {
        String account = authentication.getName();
        String password = (String) authentication.getCredentials();
        UserDto userDto = userService.findByUsername(account);
        if(userDto != null && passwordEncoder.matches(password, userDto.getPassword())){
            List<GrantedAuthority> authorities = userDto.getAuthorities().stream()
                    .map(auth->new SimpleGrantedAuthority(auth))
                    .collect(Collectors.toList());
            UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(account, null,authorities);
            auth.setDetails(userDto);
            return Mono.just(auth);
        }else {
            return Mono.error(new BadCredentialsException("用户名或密码错误！"));
        }
    }
}
